#include <vector>

using std::vector;

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int i = 0, j = 0, n = prices.size();
        int ret = 0;
        while (j < n) {
            while (i < n - 1 && prices[i] >= prices[i + 1]) {
                i++;
            }
            j = i + 1;
            while (j < n - 1 && prices[j + 1] >= prices[j]) {
                j++;
            }
            if (j < n && prices[j] > prices[i]) {
                ret += (prices[j] - prices[i]);
            }
            i = j + 1;
            if (i >= n) {
                break;
            }
        }
        return ret;
    }
};